import React, { useState, useEffect } from "react";
import { View, Text, ScrollView } from "@tarojs/components";
import CProvider from "@/components/CProvider";
import {
  ArrowLeft,
  Link,
  Location,
  Unlink,
  Refresh,
  Warning,
  WarningPolygon
} from "@nutui/icons-react-taro";
import { Button, Grid, Avatar, ActionSheet, Toast, Badge } from "@nutui/nutui-react-taro";
import {
  navigateBack,
  navigateTo,
  useRouter,
  getSystemInfo,
  openLocation,
} from "@tarojs/taro";
import { IconFont } from "@nutui/icons-react-taro";
import doFetch from "@/utils/doFetch";
import "./proteam.less";
import { useRequest } from "ahooks";

const options = [
  {
    name: "解除绑定",
  },
];

const statusMap = {
  0: "正常",
  1: "预警",
  2: "告警",
};

export default function AirConditionerControl() {
  const [isVisible, setIsVisible] = useState(false);

  const router = useRouter();
  const id = router.params.id;
  const rid = router.params.rid;
  const leave = router.params.leave;
  const remark = router.params.remark;
  const name = router.params.name;
  const link = router.params.link;

  const [loading, setLoading] = useState(false);

  const { data, refresh } = useRequest(async () => {
    let res = await doFetch({
      url: "/mini/asm_col/" + id,
      params: {},
      method: "GET",
    });

    return res?.data?.data;
  }, {});

  const handleSelect = (item) => {
    if (item.name === "解除绑定") {
      doFetch({
        url: "/mini/device_mini/" + rid,
        params: {},
        method: "DELETE",
      }).then((res) => {
        if (res?.data?.code === 0) {
          navigateBack();
        }
      });
    }
    setIsVisible(false);
  };

  const [msg, setMsg] = useState(false);

  return (
    <CProvider>
      <View className="containers">
        <ActionSheet
          title="解绑当前设备"
          cancelText="取消"
          visible={isVisible}
          options={options}
          onSelect={handleSelect}
          onCancel={() => setIsVisible(false)}
        />

        <Toast
          type="text"
          content={msg}
          duration={2}
          visible={!!msg}
          onClose={() => {
            setMsg(false)
          }}
        />

        <View className="back">
          <Button
            icon={<ArrowLeft width={20} height={20} />}
            fill="none"
            style={{ width: 40, height: 40, position: "absolute", left: 0 }}
            onClick={() => {
              navigateBack();
            }}
          ></Button>

          <View className="header">
            <Text className="title">{name}</Text>
          </View>
        </View>

        <View className="columns" style={{ margin: "66px 0 44px 0", gap: 6 }}>
          <div className="center" style={{ gap: 4 }}>
            {
              link === 'true' ? <Link style={{ color: "green" }} height={32} width={32}></Link> : <Unlink style={{ color: "#6b7280" }} height={32} width={32}></Unlink>
            }
            {link === "true" ?
              <Text
                className="status"
                style={{ color: "green" }}
              >
                在线
              </Text> :
              <Text
                className="status"
                style={{ color: "#6b7280" }}
              >
                离线
              </Text>
            }
          </div>
          {link !== "true" && <Text style={{ color: "#6b7280", textAlign: "center", fontSize: 14 }}>已于 {leave} 离线</Text>}
        </View>


        <View
          className="environment-info"
          style={{
            backgroundColor: `#e9e9e9`,
            padding: "16px 12px",
            marginBottom: 12,
          }}
        >
          <Text className="env-title">位置信息</Text>
          <View
            className="center gap-12"
            onClick={async () => {
              let res = await doFetch({
                url: `/map?key=73b3dbcaafae035c3249aa74cf3cd008&address=${remark}`,
                method: "GET",
              });
              let data = res?.data?.geocodes?.[0] ?? ",";
              const [longitude, latitude] = data?.location?.split(",");
              openLocation({
                longitude: parseFloat(longitude), // 纬度，浮动类型
                latitude: parseFloat(latitude), // 经度，浮动类型
                name: remark, // 位置名
                address: data?.formatted_address, // 地址详情说明
                scale: 12, // 地图缩放级别，范围5~18，默认为5
                success: function () {
                  console.log("打开定位成功！");
                },
                fail: function () {
                  console.log("打开定位失败！");
                },
              });
            }}
          >
            <Location />
            <Text className="env-temperature">{remark}</Text>
          </View>
        </View>

        <View
          className="environment-info"
          style={{ backgroundColor: `#e9e9e9`, padding: "16px 12px" }}
        >
          <Text className="env-title">锂电池火灾自动灭火系统 - 车棚分区 </Text>
          <Grid
            gap={10}
            columns={3}
            style={{
              width: "100%",
              marginLeft: -5,
              marginTop: 8,
              marginBottom: 4,
            }}
          >
            {data?.part_num &&
              new Array(parseInt(data?.part_num))?.fill("")?.map((_, i) => {
                const alarm = `x_part${i + 1}_alarm_status`,
                  switchs = `y_part${i + 1}_switch_status`;

                return (
                  <Grid.Item text={<Text style={{ color: data?.[alarm] === 0 ? "#000" : data?.[alarm] === 1 ? "#ecd452" : "#ff4800" }}>{statusMap[data?.[alarm]]}</Text>}>
                    <View className="center" style={{ fontSize: 14, marginBottom: 8, gap: 6 }}>
                      <Text>
                        分区 {i + 1}
                      </Text>
                      {
                        data?.[alarm] !== 0 && <Warning width={16} height={16} style={{ color: data?.[alarm] === 0 ? "#000" : data?.[alarm] === 1 ? "#ecd452" : "#ff4800" }}></Warning>
                      }
                    </View>

                    <Button
                      fill={"none"}
                      icon={
                        loading === i ?
                          <Refresh className='nut-icon-am-rotate nut-icon-am-infinite' />
                          :
                          <IconFont
                            fontClassName="iconfont"
                            classPrefix="icon"
                            name="kaiguan"
                            style={{ fontSize: 18 }}
                          />
                      }
                      onClick={async () => {
                        if (link !== "true") {
                          setMsg("设备已离线,请确保设备在线后操作")
                          return;
                        }
                        setLoading(i);
                        let res = await doFetch({
                          url: "/mini/device_mini/remote_control",
                          params: {
                            device_id: id,
                            part_num: i + 1,
                            control_type: data?.[switchs] ? "close" : "open", // open为开，close为关
                          },
                        });
                        setTimeout(async () => {
                          if (res?.data?.code === 0) {
                            let result = await doFetch({
                              url: "/mini/device_mini/refresh_out_remote_control",
                              params: {
                                device_id: id,
                              },
                              method: "GET",
                            });
                            if (result.data?.code === 0) {
                              refresh();
                              setMsg("操作成功");
                            }
                          }
                          setLoading(false);
                        }, 5000);
                      }}
                      style={
                        data?.[switchs]
                          ? {
                            backgroundColor: `#13c2c2`,
                            color: `#fff`,
                          }
                          : {
                            backgroundColor: `#f0f0f0`,
                            color: `#999`,
                          }
                      }
                    />
                  </Grid.Item>

                );
              })}
          </Grid>
        </View>

        <View
          className="power-button"
          style={{
            padding: "0 12px",
            backgroundColor: "#EE7959",
            borderRadius: 8,
          }}
          onClick={() => {
            setIsVisible(true);
          }}
        >
          <Button
            style={{
              color: `#fff`,
            }}
            size="large"
            block
            fill="none"
            icon={<Unlink style={{ fontSize: 18 }} />}
          >
            解绑
          </Button>
        </View>

        {/* <View className="mode-buttons">
          <Grid gap={10}>
            <Grid.Item text="除湿">
              <Button
                icon={<Image />}
                fill="none"
                style={{
                  backgroundColor: `#999`,
                  color: `#fff`,
                }}
              />
            </Grid.Item>
            <Grid.Item text="风扇">
              <Button
                icon={<Image />}
                fill="none"
                style={{
                  backgroundColor: `#999`,
                  color: `#fff`,
                }}
              />
            </Grid.Item>
            <Grid.Item text="修改">
              <Button icon={<Edit />} fill="none" />
            </Grid.Item>
            <Grid.Item text={<Text style={{ color: "red" }}>解绑</Text>}>
              <Button
                icon={<Image style={{ color: "red" }} />}
                type="danger"
                fill="none"
              />
            </Grid.Item>
          </Grid>
        </View> */}
        {/* <View
          className="mode-buttons"
          style={{ padding: "0 30px", borderRadius: 8 }}
        >
          <Text className="env-title">设备已关联人员</Text>
        </View>

        <View className="mode-buttons" style={{ marginBottom: 240 }}>
          <Grid gap={10}>
            {data?.minis?.map((it) => {
              return (
                <Grid.Item text={it.nick_name}>
                  <Avatar size="small" src={it.head_image} />
                </Grid.Item>
              );
            })}
          </Grid>
        </View> */}
      </View>
    </CProvider>
  );
}
